package com.haoxuer.discover.oauth.impl;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.haoxuer.discover.oauth.api.OauthHandler;
import com.haoxuer.discover.oauth.domain.TokenResponse;
import com.haoxuer.discover.oauth.domain.WeiApp;
import jodd.http.HttpRequest;


/**
 * Created by ada on 2017/6/29.
 */
public class WeiAppOauthHandler implements OauthHandler {
  
  private String oauth_consumer_key;
  
  private String secret;
  
  @Override
  public void setKey(String oauth_consumer_key) {
    this.oauth_consumer_key = oauth_consumer_key;
  }
  
  @Override
  public void setSecret(String secret) {
    this.secret = secret;
  }
  
  @Override
  public WeiApp login(String accessToken, String openid) {
    WeiApp weixin = null;
    try {
      HttpRequest request = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session");
      request.query("js_code", accessToken);
      request.query("appid", oauth_consumer_key);
      request.query("secret", secret);
      request.query("grant_type", "authorization_code");
      String body;
      body = request.send().body();
      Gson gson = new Gson();
      weixin = gson.fromJson(body, WeiApp.class);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return weixin;
    
  }
  
  @Override
  public TokenResponse getToken(String code) {
    TokenResponse result = new TokenResponse();
    try {
      HttpRequest request = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session");
      request.query("js_code", code);
      request.query("appid", oauth_consumer_key);
      request.query("secret", secret);
      request.query("grant_type", "authorization_code");
      String body;
      body = request.send().body();
      JsonParser parser = new JsonParser();
      JsonElement element = parser.parse(body);
      result.setAccessToken(ElementUtils.getString(element, "session_key"));
      result.setRefreshToken(ElementUtils.getString(element, "refresh_token"));
      result.setTokenType("weiapp");
      result.setExpiresIn(ElementUtils.getInt(element, "expires_in"));
      result.setOpenId(ElementUtils.getString(element, "openid"));
      result.setUnionid(ElementUtils.getString(element, "unionid"));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
}
